<?php
session_start();
require_once 'database.php';
header('Content-Type: application/json');

function default_response($data = [], $status = 'success', $code = 200)
{
    http_response_code($code);
    echo json_encode(array_merge(['status' => $status], $data));
}

function batchAddRegistrations($training_id, $teacherIds)
{
    global $pdo;
    $datas = array();

    if ($_SESSION['username'] == 'admin') {

        // 通过$training_id和$school获取所有 teacher_id
        $stmt = $pdo->prepare('SELECT teacher_id FROM trainings_teachers WHERE training_id = ?');
        $stmt->execute([$training_id]);
        $original_teacherIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $del_teacherIds = array_diff($original_teacherIds, $teacherIds);
        // 删除旧数据
        if (!empty($del_teacherIds)) {
            $stmt = $pdo->prepare('DELETE FROM trainings_teachers WHERE teacher_id IN (' . implode(',', $del_teacherIds) . ') AND training_id = ?');
            $stmt->execute([$training_id]);
        }
    } else {

        $school = $_SESSION['school'];
        // 通过$training_id和$school获取所有 teacher_id
        $stmt = $pdo->prepare('SELECT teacher_id FROM trainings_teachers WHERE training_id = ? AND teacher_school = ?');
        $stmt->execute([$training_id, $school]);
        $original_teacherIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $del_teacherIds = array_diff($original_teacherIds, $teacherIds);
        // 删除旧数据
        if (!empty($del_teacherIds)) {
            $stmt = $pdo->prepare('DELETE FROM trainings_teachers WHERE teacher_id IN (' . implode(',', $del_teacherIds) . ') AND training_id = ? AND teacher_school = ?');
            $stmt->execute([$training_id, $school]);
        }
    }
    $add_teacherIds = array_diff($teacherIds, $original_teacherIds);
    if (!empty($add_teacherIds)) {
        // 由 teacherIds 查询teachers表中的数据     here_work_time TEXT,
        $stmt = $pdo->prepare('SELECT id, name, subject, work_time, phone, sex, birthday, school, grade, major, educational, qualifications, master_level FROM teachers WHERE id IN (' . implode(',', $add_teacherIds) . ')');
        if ($stmt->execute()) {
            $teachers = $stmt->fetchAll(PDO::FETCH_NUM);
            foreach ($teachers as $teacher) {
                $teacher[] = $training_id;
                $datas[] = $teacher;
            }
        }

        $stmt = $pdo->prepare("INSERT INTO trainings_teachers (teacher_id, teacher_name, teacher_subject, teacher_work_time, teacher_phone, teacher_sex, teacher_birthday, teacher_school, teacher_grade, teacher_major, teacher_educational, teacher_qualifications, teacher_master_level, training_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        foreach ($datas as $data) {
            $stmt->execute($data);
        }
    }
    return true;
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);

        // 处理批量报名
        if (isset($input['action']) && $input['action'] === 'batch_register') {
            if (isset($input['teacherIds']) && is_array($input['teacherIds'])) {
                if (batchAddRegistrations($input['training_id'], $input['teacherIds'])) {
                    default_response(["message" => "批量报名成功"]);
                } else {
                    default_response(["message" => "批量报名失败"], "error", 500);
                }
            } else {
                default_response(["message" => "无效的报名数据"], "error", 400);
            }
        } else {
            default_response(["message" => "无效的请求"], "error", 400);
        }
    }
} catch (Exception $e) {
    default_response(["message" => $e->getMessage()], "error", 500);
}
